package com.dl.study.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author: user
 * @Date: 2021/10/20 15:02
 * @Description:
 */

@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        String token = request.getHeaders().getFirst("x-token");
        if (StringUtils.isBlank(token)) {
            return out(response);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -20;
    }

    // 使用webflux输入请求信息
    private Mono<Void> out(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
        JSONObject message = new JSONObject();
        message.put("success", false);
        message.put("code", 28004);
        message.put("data", null);
        message.put("message", "鉴权失败");
        DataBuffer buffer = response.bufferFactory().wrap(message.toJSONString().getBytes((StandardCharsets.UTF_8)));
        //返回这个，就不会再执行filter了，就是真的返回了
        return response.writeWith(Mono.just(buffer));
    }
}
